import { useState, useEffect } from "react";
import React from 'react';
import {
  useNavigate,
  useLocation,
} from "react-router-dom";
import {
  AppstoreOutlined,
  SettingOutlined,
  BarChartOutlined,
  CloudOutlined,
  ShopOutlined,
  TeamOutlined,
  UploadOutlined,
  UserOutlined,
  VideoCameraOutlined,
  KeyOutlined,
} from '@ant-design/icons';
import { Menu, theme, Layout, Button, message } from "antd";
import { LogoutOutlined } from '@ant-design/icons';
import MyRoute from "./Routes/router";
import { FileExcelOutlined } from "@ant-design/icons/lib";
import { api, queryList } from "./api/api";
import Url from "./api/url";
import { Modal } from "antd";
import { Form } from "antd";
import { Input } from "antd";

const { Header, Content, Footer, Sider } = Layout;

function App() {
  // const [count, setCount] = useState(0);
  // const [itemLable, setItemLable] = useState();
  const navigate = useNavigate();
  const location = useLocation();
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [currentTitle, setCurrentTitle] = useState("/");
  const [items, setItems] = useState([]);
    // 添加状态控制 Modal 显示
  const [pwdModalVisible, setPwdModalVisible] = useState(false);
  const [pwdForm] = Form.useForm();
  const user = JSON.parse(localStorage.getItem('user'))

  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();

  const defaultItems = [
    
    {
      label: "系统管理",
      icon: <AppstoreOutlined />,
      children:[
        {
          label:"用户管理",
          key:"/setting/userPage"
        },{
          label:"角色管理",
          key:"/setting/rolePage"
        },{
          label: "数据导入",
          key: "/setting/importExcel",
          // icon: <FileExcelOutlined />,
        },{
          label: "客户对应品种",
          key: "/setting/custOfProdPage",
          // icon: <FileExcelOutlined />,
        },
      ]
    },{
      label:"流向查询",
      icon: <AppstoreOutlined />,
      children:[
        {
          label: "销售流向",
          key: "/flow/saleFlowPage",
          icon: <AppstoreOutlined />,
        },{
          label: "采购流向",
          key: "/flow/purFlowPage",
          icon: <AppstoreOutlined />,
        },
      ]

    },{
      label:"库存查询",
      icon: <AppstoreOutlined />,
      children:[
        {
          label: "库存查询",
          key: "/store/storePage",
          icon: <AppstoreOutlined />,
        },{
          label: "批次库存查询",
          key: "/store/lotStorePage",
          icon: <AppstoreOutlined />,
        },
      ]

    }
  ];

  const pageLoad = async () =>{
     // 检查登录状态
    const token = localStorage.getItem('token');
    if (!token && location.pathname !== '/login') {
      navigate('/login');
    } else if (token) {
      setIsLoggedIn(true);

      if(location.pathname === '/'){
        // const user = JSON.parse(localStorage.getItem('user') || '[]');
        const pkList = user.ROLES.split(',')
        const res = await api({url:Url.getMenuByRole,data:{pkList:pkList}})

        // 根据后端返回的菜单权限过滤菜单
        const filterMenus = defaultItems.filter(item => {
          const children = item.children?.filter(child => 
            res.data.some(menu => menu.MENU_PATH === child.key)
          );
          return children && children.length > 0;
        }).map(item => ({
          ...item,
          children: item.children.filter(child =>
            res.data.some(menu => menu.MENU_PATH === child.key)
          )
        }));

        setItems(filterMenus);
      }
    }
  }

    // 添加修改密码处理函数
  const handleChangePwd = async () => {
    try {
      const values = await pwdForm.validateFields();
      if (values.newPassword !== values.confirmPassword) {
        message.error('两次输入的密码不一致');
        return;
      }

      const user = JSON.parse(localStorage.getItem('user'))
      
      const res = await api({
        url: Url.changePwd,
        data: {
          PK: user.PK,
          oldPassword: values.oldPassword,
          newPassword: values.newPassword
        }
      });
      
      message.success('密码修改成功,请重新登录');
      setPwdModalVisible(false);
      // 清除登录信息
      localStorage.removeItem('token');
      navigate('/login');
    } catch (error) {
      console.log('修改密码失败:', error);
    }
  };

  useEffect( () =>  {
    pageLoad()
  }, [location.pathname]);


    

  // 如果未登录且不在登录页面，显示登录页面
  if (!isLoggedIn && location.pathname !== '/login') {
    return <MyRoute />;
  }

  // 如果在登录页面，直接显示登录组件
  if (location.pathname === '/login') {
    return <MyRoute />;
  }

  // 以下是已登录状态的布局
  const siderStyle = {
  overflow: 'auto',
  height: '100vh',
  position: 'sticky',
  insetInlineStart: 0,
  top: 0,
  bottom: 0,
  scrollbarWidth: 'thin',
  scrollbarGutter: 'stable',
};


  

  

  const onClick = (e) => {
    setCurrentTitle(e.key);
    // setItemLable(e.key);
    navigate(e.key);
  };

  return (
    <Layout hasSider>      
    <Sider style={siderStyle}>
        <div className="demo-logo-vertical" />
        <div className="sider-content" style={{display: 'flex',flexDirection: 'column',height: '100%',justifyContent: 'space-between'}}>
          <Menu theme="dark" mode="inline" defaultSelectedKeys={['1']} items={items} onClick={onClick} />
          <div className="logout-button-container" style={{padding: "16px"}} >

            <Button style={{ width: '100%',marginBottom:10, color:"white",
               justifyContent: "flex-start", // 添加这行
                display: "flex",              // 添加这行
                alignItems: "center"
             }} 
            type="text"
            >
              {user.CUSTOMER_NAME}</Button>

            <Button style={{ width: '100%',marginBottom:10 }}
              type="primary"
              icon={<KeyOutlined />}
              onClick={() => setPwdModalVisible(true)}
              >修改密码</Button>

            <Button
              style={{ width: '100%' }}
              type="primary"
              danger
              icon={<LogoutOutlined />}
              onClick={() => {
                localStorage.removeItem('token');
                navigate('/login');
              }}
            >
              退出登录
            </Button>
          </div>
        </div>
      </Sider>

      {/* 添加修改密码的 Modal */}
      <Modal
        title="修改密码"
        open={pwdModalVisible}
        onOk={handleChangePwd}
        onCancel={() => {
          setPwdModalVisible(false);
          pwdForm.resetFields();
        }}
        okText="确定"
        cancelText="取消"
      >
        <Form
          form={pwdForm}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          clearOnDestroy
        >
          <Form.Item
            label="原密码"
            name="oldPassword"
            rules={[{ required: true, message: '请输入原密码' }]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            label="新密码"
            name="newPassword"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, message: '密码长度不能小于6位' }
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            label="确认密码"
            name="confirmPassword"
            rules={[
              { required: true, message: '请确认新密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password />
          </Form.Item>
        </Form>
      </Modal>

      <Layout>
        {/* <Header style={{ padding: 0, background: colorBgContainer }} /> */}
        <Content style={{ margin: '24px 16px 0', overflow: 'initial' }}>

          <div
          style={{
            // padding: "8px 24px 24px 24px",
            // minHeight: window.innerHeight - 69,
            background: colorBgContainer,
            borderRadius: borderRadiusLG,
          }}
        >
          <MyRoute />
        </div>


        </Content>
        {/* <Footer style={{ textAlign: 'center' }}>
          Copyright  ©{new Date().getFullYear()} 山西澜宇医药有限公司 All Rights Reserved
        </Footer> */}
      </Layout>
      


      
      {/* <Header
        style={{
          position: "sticky",
          top: 0,
          zIndex: 1,
          width: "100%",
          display: "flex",
          alignItems: "center",
          padding: 5,
          fontWeight: "bold",
        }}
      >
        <img
          width={65}
          // src="https://zeuspmp.obs.cn-north-4.myhwclouds.com/1755040802888138753.png" //牛九
          src="https://nn.jztweb.com/static/media/logo3.3ac4d21d.png"  //牛牛
          // src="https://zeus.jztweb.com/zsCloud/res/images/wt.png" //沃土
        ></img>
        <Menu
          onClick={onClick}
          selectedKeys={[currentTitle]}
          // style={{ userSelect: "none" }}
          mode="horizontal"
          items={items}
          theme="dark"
          // selectable={false}
        />
      </Header> */}


      {/* <Content style={{ padding: "0 0" }}>
        {<Breadcrumb style={{ margin: '16px 0' }} items={[{title: '首页'}]}/>}
        <div
          style={{
            padding: "8px 24px 24px 24px",
            minHeight: window.innerHeight - 69,
            background: colorBgContainer,
            borderRadius: borderRadiusLG,
          }}
        >
          <MyRoute />
        </div>
      </Content> */}


      {/*    <Footer style={{ textAlign: "center" }}>
        NineBelieveGroup ©{new Date().getFullYear()} Created by lz
      </Footer> */}
    </Layout>

    



  );
}

export default App;
